package com.chb.link;

/**
 * 此测试中的链表是没有头结点的
 */
public class TestLink {
    public static void main(String[] args) {
        TestLink tl = new TestLink();
        SingleListNode head = new SingleListNode(1);
        SingleListNode n2 = new SingleListNode(2);
        SingleListNode n3 = new SingleListNode(3);
        SingleListNode n4 = new SingleListNode(4);

        head.next = n2;
        n2.next = n3;
        // n3.next = n4;
        tl.showLink(head);
        SingleListNode newHead = tl.swapPairs(head);
        tl.showLink(newHead);
    }

    /**
     * 打印链表
     *
     * @param head
     */
    public void showLink(SingleListNode head) {
        while (head != null) {
            String split = "->";
            if (head.next == null) split = "";
            System.out.print(head.val + split);
            head = head.next;
        }
        System.out.println();
    }


    /**
     * 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。
     * <p>
     * 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。
     *
     * @param head
     * @return
     * @see https://leetcode-cn.com/problems/swap-nodes-in-pairs/
     */
    public SingleListNode swapPairs(SingleListNode head) {
        SingleListNode t1 = head;
        SingleListNode newHead = null;

        SingleListNode t = null;
        while (t1 != null) {
            SingleListNode t2 = t1.next;
            if (t2 == null) {
                if (newHead == null) {
                    newHead = t1;
                } else {
                    t.next = t1;
                }
                break;
            } else {
                SingleListNode tmp = t2.next;
                t2.next = t1;
                t1.next = null;

                System.out.println(t1.val + "==" + t2.val + "==" + t2.next.val);
                if (newHead == null) {
                    newHead = t2;
                } else {
                    System.out.println(t + "==" + t2);
                    t.next = t2;
                }
                t = t1;
                t1 = tmp;
                System.out.println("t = " + t.val + "==" + t + "===" + t1);
            }
        }
        return newHead;
    }
}
